/**
 * Copyright (C) 2011 Moss Computing <support@mosscomputing.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.oslef.csv;

import java.util.LinkedList;
import java.util.List;

public final class RowParser {
	/**
	 * 
	 * @param line A line of CSV text.
	 * @param delimiter The delimiter character used to distinguish between fields
	 * @return null if the line was incomplete (i.e. if the last field continues past the end of the line).  Otherwise, returns a String array containing the value of each field.
	 */
	public static String[] parse(String line, char delimiter){
		boolean lineWasComplete;
		
		List<String> fields = new LinkedList<String>();
		
		StringBuffer field = new StringBuffer();
		char c;
		boolean inQuotes = false;
		boolean fieldOpen = true;
		for(int x=0;x<line.length();x++){
			c = line.charAt(x);
			if(c==delimiter && !inQuotes){
				fields.add(field.toString());
				field = new StringBuffer();
				fieldOpen=true;
			}else if(c=='"' && !inQuotes){
				inQuotes = true;
			}else if(c=='"'){
				if(x>0 && line.charAt(x-1)=='\\'){
					// this is an escaped quote
					field.append(c);
				}else{
					inQuotes = false;
				}
//				fieldOpen=false;
			}else{
				field.append(c);
			}
		}
		if(fieldOpen){
			fields.add(field.toString());
			if(inQuotes){
				lineWasComplete = false;
			}else{
				lineWasComplete = true;
			}
		}else{
			lineWasComplete = true;
		}
		if(lineWasComplete){
			return fields.toArray(new String[]{});
		}else{
			return null;
		}
	}
}
